package com.eps.security;

import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import javax.servlet.*;
import java.io.IOException;

public class SecurityFilter extends AbstractSecurityInterceptor implements Filter {

    //    AccessDecisionManager和AuthenticationManager这两个成员变量已经在父类中声明了，所以只需声明FilterInvocationSecurityMetadataSource
    private FilterInvocationSecurityMetadataSource securityMetadataSource = null;

    public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
        return securityMetadataSource;
    }

    public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
        this.securityMetadataSource = securityMetadataSource;
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return securityMetadataSource;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("自定义Filter初始化");
    }

    @Override
    public void destroy() {
        System.out.println("自定义Filter销毁");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
        Invoke(fi);
    }

    public void Invoke(FilterInvocation fi) throws IOException, ServletException {
        //这里是做安全检查的地方
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            //接着向拦截器链执行
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }
    }

}
